package com.bjfu.eduorder.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjfu.eduorder.entity.Order;
import com.bjfu.eduorder.entity.PayLog;
import com.bjfu.eduorder.mapper.PayLogMapper;
import com.bjfu.eduorder.service.OrderService;
import com.bjfu.eduorder.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjfu.eduorder.utils.HttpClient;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author Guli
 * @since 2020-07-18
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {
    @Autowired
    private OrderService orderService;

    @Resource
    private RedisTemplate<String,Map> redisTemplate;

    @Override
    public Map createNative(String orderNo) {
        Map terminalResult = redisTemplate.opsForValue().get(orderNo);
        if (terminalResult != null) {
            return terminalResult;
        }
        try{
            // 1.根据订单号查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<Order>();
            wrapper.eq("order_no",orderNo);
            Order order = orderService.getOne(wrapper);
            // 2.使用map设置生成二维码需要参数
            Map map = new HashMap<>();
            map.put("appid", "wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", order.getCourseTitle()); //课程标题
            map.put("out_trade_no", orderNo); //订单号
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");// 订单价格,先变成long类型,再变成字符串类型
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            map.put("trade_type", "NATIVE");
            
            // 3.发送httpclient请求,传递参数xml格式,微信提供固定api地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // 设置xml格式的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行post请求发送
            client.post();

            // 4.得到发送请求结果并返回
            // 返回的内容是xml格式返回的
            String content = client.getContent();
            System.out.println("***************订单结果*******************");
            System.out.println(content);
            System.out.println("***************end*******************");
            // 把xml格式转换为map集合,把map集合返回
            Map<String,String> resultMap = new HashMap<>();
            resultMap = WXPayUtil.xmlToMap(content);

            // 最终返回数据的封装
            terminalResult = new HashMap();
            terminalResult.put("out_trade_no", orderNo);
            terminalResult.put("course_id", order.getCourseId());
            terminalResult.put("total_fee", order.getTotalFee());
            terminalResult.put("result_code", resultMap.get("result_code"));
            terminalResult.put("code_url", resultMap.get("code_url"));

            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            redisTemplate.opsForValue().set(orderNo, terminalResult, 120, TimeUnit.MINUTES);
            // TODO
            // 取消订单
            return terminalResult;
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"支付二维码生成失败");
        }
    }

    // 查询订单状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try{
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            // 2.发送请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            // 3.得到请求返回的内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"未能获取支付状态");
        }
    }

    @Override
    public void updateOrderStatus(Map<String, String> map) {
        try {
            // 从map中获取订单号
            String orderNo = map.get("out_trade_no");
            QueryWrapper<Order> wrapper = new QueryWrapper<Order>();
            wrapper.eq("order_no",orderNo);
            Order order = orderService.getOne(wrapper);

            // 更新订单表订单状态
            if(order.getStatus().intValue() == 1) return;
            else {
                order.setStatus(1); // 代表已经支付
                orderService.updateById(order);

                // 向支付表添加支付记录
                PayLog payLog = new PayLog();
                payLog.setOrderNo(orderNo);
                payLog.setPayTime(new Date()); //订单完成时间
                payLog.setTotalFee(order.getTotalFee()); // 订单总金额
                payLog.setTransactionId(map.get("trade_transaction_id")); //订单流水号
                payLog.setTradeState(map.get("trade_state")); //订单咋混太
                payLog.setPayType(1);
                payLog.setAttr(JSONObject.toJSONString(map));// 其他属性
                baseMapper.insert(payLog);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}
